import random
import xlrd
import tkinter as tk
from tkinter import ttk, messagebox
import ttkbootstrap as ttk

# 加载Excel数据表
def load_tables():
    data = xlrd.open_workbook('direct_chariot.xlsx')
    tables = [data.sheets()[i] for i in range(14)]  # 加载所有表
    return tables

tables = load_tables()

# 直瞄武器打击分析
def direct_attack_analysis():
    def calculate():
        try:
            W = int(weapon_combobox.get().split('.')[0])
            hp = int(squad_entry.get())
            L = int(distance_entry.get())
            H = int(height_entry.get())
            R_delta = int(random_correction_entry.get())
            df = int(armor_combobox.get().split('.')[0])

            P = [0] * 10  # 概率分布
            S = 0.0  # 期望值

            # 确定攻击等级
            if df == 6:
                AL0 = tables[6].cell_value(4 * (W - 1) + hp, L + 2)  # 对人
            else:
                if W == 13:
                    W = W + hp - 1
                AL0 = tables[3].cell_value(W, L + 1)  # 对车

            AL = AL0 + tables[4].cell_value(H + 1, L + 1)

            if AL <= 0:
                result_text.insert(tk.END, '攻击等级为0，无法造成伤害\n')
            else:
                if df == 6:
                    # 直瞄武器对人打击分析
                    for x in range(2, 13):
                        P0 = tables[0].cell_value(x - 1, 1)
                        D0 = tables[5].cell_value(x, int(AL))
                        for y in range(1, 7):
                            P1 = 6
                            R = y + R_delta
                            D_delta = -1 if R <= 0 else (1 if R >= 8 else 0)
                            D = D0 + D_delta
                            M = 0 if D <= 0.1 else round(D + 1)
                            P[int(M)] += (P0 * P1) / 1296
                else:
                    # 直瞄武器对车打击分析
                    for i in range(2, 13):
                        P0 = tables[0].cell_value(i - 1, 1)
                        if W == 13:
                            D0 = tables[5].cell_value(i, AL)
                        else:
                            for n in range(1, 20):
                                if tables[1].cell_value(hp, n) == AL:
                                    D0 = tables[1].cell_value(i + 5, n)
                        for j in range(2, 13):
                            P1 = tables[0].cell_value(j - 1, 1)
                            R = j + R_delta
                            k = 2 if R <= -3 else (3 if -2 <= R <= -1 else (4 if R == 0 else (5 if R == 1 else (6 if R == 2 else (7 if 3 <= R <= 5 else (8 if 6 <= R <= 8 else (9 if R == 9 else (10 if R == 10 else (11 if R == 11 else 12)))))))))
                            D_delta = tables[2].cell_value(k, df)
                            D = D0 + D_delta
                            M = 0 if D <= 0.1 else round(D + 1)
                            P[int(M)] += (P0 * P1) / 1296

                # 输出概率分布和期望值
                result_text.insert(tk.END, '------------------------------------\n')
                for m in range(10):
                    if P[m] > 0:
                        if m == 0:
                            result_text.insert(tk.END, f'无效的概率为：{round(100 * P[m], 1)}%\n')
                        elif m == 1:
                            result_text.insert(tk.END, f'战损0的概率为：{round(100 * P[m], 1)}%\n')
                        else:
                            result_text.insert(tk.END, f'战损{m - 1}的概率为：{round(100 * P[m], 1)}%\n')
                            S += (m - 1) * P[m]
                result_text.insert(tk.END, f'战损期望值为：{round(S, 2)}\n')
            result_text.insert(tk.END, '=================================================\n')
        except Exception as e:
            messagebox.showerror("错误", f"输入无效: {e}")

    # 创建直瞄武器窗口
    direct_window = tk.Toplevel()
    direct_window.title("直瞄武器打击分析")
    
    # 武器类型
    tk.Label(direct_window, text="武器类型:").grid(row=0, column=0, padx=5, pady=5)
    weapon_options = [
        "1.大号直瞄炮", "2.中号直瞄炮", "3.小号直瞄炮", "4.速射炮", "5.火箭筒",
        "6.便携导弹", "7.车载导弹", "8.重型导弹", "9.中型导弹标准", "10.中型导弹便携",
        "11.小型导弹", "12.巡飞弹", "13.步兵轻武器"
    ]
    weapon_combobox = ttk.Combobox(direct_window, values=weapon_options)
    weapon_combobox.grid(row=0, column=1, padx=5, pady=5)
    weapon_combobox.set(weapon_options[0])
    
    # 班组数
    tk.Label(direct_window, text="班组数:").grid(row=1, column=0, padx=5, pady=5)
    squad_entry = tk.Entry(direct_window)
    squad_entry.grid(row=1, column=1, padx=5, pady=5)
    
    # 距离
    tk.Label(direct_window, text="距离:").grid(row=2, column=0, padx=5, pady=5)
    distance_entry = tk.Entry(direct_window)
    distance_entry.grid(row=2, column=1, padx=5, pady=5)
    
    # 高度差
    tk.Label(direct_window, text="高度差:").grid(row=3, column=0, padx=5, pady=5)
    height_entry = tk.Entry(direct_window)
    height_entry.grid(row=3, column=1, padx=5, pady=5)
    
    # 随机数修正值
    tk.Label(direct_window, text="随机数修正值:").grid(row=4, column=0, padx=5, pady=5)
    random_correction_entry = tk.Entry(direct_window)
    random_correction_entry.grid(row=4, column=1, padx=5, pady=5)
    
    # 装甲等级
    tk.Label(direct_window, text="装甲等级:").grid(row=5, column=0, padx=5, pady=5)
    armor_options = ["1.复合装甲", "2.重型装甲", "3.中型装甲", "4.轻型装甲", "5.无装甲", "6.人"]
    armor_combobox = ttk.Combobox(direct_window, values=armor_options)
    armor_combobox.grid(row=5, column=1, padx=5, pady=5)
    armor_combobox.set(armor_options[0])
    
    # 计算和清除按钮
    button_frame = tk.Frame(direct_window)
    button_frame.grid(row=6, column=0, columnspan=2, pady=10)
    
    calculate_button = tk.Button(button_frame, text="计算", command=calculate)
    calculate_button.pack(side="left", padx=5)
    
    clear_button = tk.Button(button_frame, text="清除", command=lambda: result_text.delete(1.0, tk.END))
    clear_button.pack(side="left", padx=5)
    
    # 结果显示
    result_text = tk.Text(direct_window, height=15, width=50)
    result_text.grid(row=7, column=0, columnspan=2, padx=5, pady=5)

# 间瞄计划分析
def indirect_attack_analysis():
    def calculate():
        try:
            L = int(distance_entry.get())
            V = int(correction_type_combobox.get().split('.')[0])
            W = int(weapon_combobox.get().split('.')[0])
            hp0 = int(squad_entry.get())
            df0 = int(armor_combobox.get().split('.')[0])
            R_delta = int(terrain_correction_entry.get())

            P = [0] * 6  # 战损概率分布
            Q = [0] * 6  # 散布概率分布
            QQ = [0] * 6  # 命中情况未知概率分布
            S = 0.0  # 期望值
            SS = 0.0  # 总期望值

            # 命中情况概率分布
            y = 1 if L <= 20 else (2 if 21 <= L <= 40 else (3 if 41 <= L <= 60 else 4))

            if V == 1:
                for x in range(2, 13):
                    Q0 = tables[0].cell_value(x - 1, 1)
                    G = tables[9].cell_value(x, y)
                    Q[int(G)] += Q0 / 36
            elif V == 2:
                for x in range(2, 13):
                    Q0 = tables[0].cell_value(x - 1, 1)
                    G = tables[10].cell_value(x, y)
                    Q[int(G)] += Q0 / 36
            else:
                for x in range(2, 13):
                    Q0 = tables[0].cell_value(x - 1, 1)
                    G = tables[11].cell_value(x, 1)
                    Q[int(G)] += Q0 / 36

            result_text.insert(tk.END, '------------------------------------\n')
            result_text.insert(tk.END, '火炮命中概率分布：\n')
            for n in range(6):
                if n == 0:
                    result_text.insert(tk.END, f'命中的概率为：{round(100 * Q[n], 1)}%\n')
                elif n == 1:
                    result_text.insert(tk.END, f'偏移的概率为：{round(100 * Q[n], 1)}%\n')
                else:
                    result_text.insert(tk.END, f'散布{n - 1}格的概率为：{round(100 * Q[n], 1)}%\n')
            result_text.insert(tk.END, '------------------------------------\n')

            # 不同命中情况下战损概率分布
            if hp0 == 1:
                hp = -4
            elif hp0 == 2:
                hp = -2
            elif hp0 == 3:
                hp = 0
            elif hp0 == 4:
                hp = 2
            else:
                raise ValueError("火炮数量输入错误")

            if df0 == 1:
                df = -3
            elif df0 == 2:
                df = -1
            elif df0 == 3 or df0 == 5:
                df = 0
            elif df0 == 4:
                df = 1
            else:
                raise ValueError("目标装甲输入错误")

            for T in range(2):
                O = '命中' if T == 0 else '偏离'
                for i in range(2, 13):
                    P0 = tables[0].cell_value(i - 1, 1)
                    D0 = tables[7].cell_value(i, W) if T == 0 else tables[8].cell_value(i, W)
                    for j in range(1, 7):
                        P1 = 6
                        R = j + R_delta + df + hp
                        D_delta = -2 if R <= 1 else (-1 if 2 <= R <= 4 else (0 if 5 <= R <= 7 else 1))
                        D = D0 + D_delta
                        M = 0 if D <= 0.1 else round(D + 1)
                        P[int(M)] += (P0 * P1) / 1296

                result_text.insert(tk.END, '------------------------------------\n')
                result_text.insert(tk.END, f'火炮<{O}>时的战损概率分布：\n')
                for m in range(6):
                    if m == 0:
                        result_text.insert(tk.END, f'无效的概率为：{round(100 * P[m], 1)}%\n')
                    elif m == 1:
                        result_text.insert(tk.END, f'战损0的概率为：{round(100 * P[m], 1)}%\n')
                    else:
                        result_text.insert(tk.END, f'战损{m - 1}的概率为：{round(100 * P[m], 1)}%\n')
                        S += (m - 1) * P[m]
                result_text.insert(tk.END, f'战损期望值为：{round(S, 2)}\n')
                for n in range(6):
                    QQ[n] += Q[T] * P[n]
                SS += S * Q[T]
                P = [0] * 6
                S = 0.0

            result_text.insert(tk.END, '------------------------------------\n')
            QQ[0] += sum(Q[2:6])
            result_text.insert(tk.END, '命中情况<未知>时的战损概率分布：\n')
            for k in range(6):
                if k == 0:
                    result_text.insert(tk.END, f'无效的概率为：{round(100 * QQ[k], 1)}%\n')
                elif k == 1:
                    result_text.insert(tk.END, f'战损0的概率为：{round(100 * QQ[k], 1)}%\n')
                else:
                    result_text.insert(tk.END, f'战损{k - 1}的概率为：{round(100 * QQ[k], 1)}%\n')
            result_text.insert(tk.END, f'总战损期望值为：{round(SS, 2)}\n')
            result_text.insert(tk.END, '------------------------------------\n')

            # 批量间瞄统计
            if batch_var.get() == 1:
                pao_N = int(artillery_entry.get())
                ZZ = int(target_type_combobox.get().split('.')[0])
                N = int(count_entry.get())
                PP = [0] * (4 * pao_N + 1)
                S = 0
                SS = 0

                for i in range(N):
                    for j in range(pao_N):
                        PPn = random.random()
                        if PPn <= QQ[0]:
                            S += 0
                        elif PPn <= (QQ[0] + QQ[1]):
                            S += 0.1 if ZZ == 2 else 0.01
                        elif PPn <= (QQ[0] + QQ[1] + QQ[2]):
                            S += 1
                        elif PPn <= (QQ[0] + QQ[1] + QQ[2] + QQ[3]):
                            S += 2
                        elif PPn <= (QQ[0] + QQ[1] + QQ[2] + QQ[3] + QQ[4]):
                            S += 3
                        else:
                            S += 4
                    k = 0 if S == 0 else (1 if 0 < S < 1 else S + 1)
                    PP[int(k)] += 1 / N
                    S = 0

                result_text.insert(tk.END, '批量间瞄统计结果：\n')
                for x in range(4 * pao_N):
                    if PP[x] > 0:
                        if x == 0:
                            result_text.insert(tk.END, f'无效的概率为：{round(100 * PP[x], 1)}%\n')
                        else:
                            SS += (x - 1) * PP[x]
                            result_text.insert(tk.END, f'战损{x - 1}的概率为：{round(100 * PP[x], 1)}%\n')
                result_text.insert(tk.END, f'总伤害期望值为：{round(SS, 2)}\n')
            result_text.insert(tk.END, '===========================================================\n')
        except Exception as e:
            messagebox.showerror("错误", f"输入无效: {e}")

    # 创建间瞄计划窗口
    indirect_window = tk.Toplevel()
    indirect_window.title("间瞄计划分析")
    
    # 射击距离
    tk.Label(indirect_window, text="射击距离:").grid(row=0, column=0, padx=5, pady=5)
    distance_entry = tk.Entry(indirect_window)
    distance_entry.grid(row=0, column=1, padx=5, pady=5)
    
    # 校射类型
    tk.Label(indirect_window, text="校射类型:").grid(row=1, column=0, padx=5, pady=5)
    correction_type_options = ["1.无校射", "2.格内校射", "3.目标校射"]
    correction_type_combobox = ttk.Combobox(indirect_window, values=correction_type_options)
    correction_type_combobox.grid(row=1, column=1, padx=5, pady=5)
    correction_type_combobox.set(correction_type_options[0])
    
    # 间瞄武器
    tk.Label(indirect_window, text="间瞄武器:").grid(row=2, column=0, padx=5, pady=5)
    weapon_options = ["1.轻型炮", "2.中型炮", "3.重型炮"]
    weapon_combobox = ttk.Combobox(indirect_window, values=weapon_options)
    weapon_combobox.grid(row=2, column=1, padx=5, pady=5)
    weapon_combobox.set(weapon_options[0])
    
    # 班组数
    tk.Label(indirect_window, text="班组数:").grid(row=3, column=0, padx=5, pady=5)
    squad_entry = tk.Entry(indirect_window)
    squad_entry.grid(row=3, column=1, padx=5, pady=5)
    
    # 目标装甲
    tk.Label(indirect_window, text="目标装甲:").grid(row=4, column=0, padx=5, pady=5)
    armor_options = ["1.复合装甲", "2.重型装甲", "3.中型装甲", "4.轻型装甲", "5.无装甲"]
    armor_combobox = ttk.Combobox(indirect_window, values=armor_options)
    armor_combobox.grid(row=4, column=1, padx=5, pady=5)
    armor_combobox.set(armor_options[0])
    
    # 地形修正值
    tk.Label(indirect_window, text="地形修正值:").grid(row=5, column=0, padx=5, pady=5)
    terrain_correction_entry = tk.Entry(indirect_window)
    terrain_correction_entry.grid(row=5, column=1, padx=5, pady=5)
    
    # 批量间瞄统计
    batch_var = tk.IntVar()
    batch_check = tk.Checkbutton(indirect_window, text="批量间瞄统计", variable=batch_var)
    batch_check.grid(row=6, column=0, columnspan=2, pady=5)
    
    # 炮兵数目
    tk.Label(indirect_window, text="炮兵数目:").grid(row=7, column=0, padx=5, pady=5)
    artillery_entry = tk.Entry(indirect_window)
    artillery_entry.grid(row=7, column=1, padx=5, pady=5)
    
    # 攻击对象
    tk.Label(indirect_window, text="攻击对象:").grid(row=8, column=0, padx=5, pady=5)
    target_type_options = ["1.车辆", "2.步兵"]
    target_type_combobox = ttk.Combobox(indirect_window, values=target_type_options)
    target_type_combobox.grid(row=8, column=1, padx=5, pady=5)
    target_type_combobox.set(target_type_options[0])
    
    # 统计次数
    tk.Label(indirect_window, text="统计次数:").grid(row=9, column=0, padx=5, pady=5)
    count_entry = tk.Entry(indirect_window)
    count_entry.grid(row=9, column=1, padx=5, pady=5)
    
    # 计算和清除按钮
    button_frame = tk.Frame(indirect_window)
    button_frame.grid(row=10, column=0, columnspan=2, pady=10)
    
    calculate_button = tk.Button(button_frame, text="计算", command=calculate)
    calculate_button.pack(side="left", padx=5)
    
    clear_button = tk.Button(button_frame, text="清除", command=lambda: result_text.delete(1.0, tk.END))
    clear_button.pack(side="left", padx=5)
    
    # 结果显示
    result_text = tk.Text(indirect_window, height=20, width=60)
    result_text.grid(row=11, column=0, columnspan=2, padx=5, pady=5)

# 防空武器分析
def air_defense_analysis():
    def calculate():
        try:
            W = int(weapon_combobox.get().split('.')[0])
            g = int(distance_entry.get())
            L = 22 if 21 <= g <= 50 else g + 1
            AL = tables[12].cell_value(W, L)
            P = [0] * 2
            for i in range(2, 13):
                P0 = tables[0].cell_value(i - 1, 1)
                D = tables[13].cell_value(i, int(AL))
                P[int(D)] += P0 / 36

            result_text.insert(tk.END, '------------------------------------\n')
            for j in range(2):
                if j == 0:
                    result_text.insert(tk.END, f'无效的概率为：{round(100 * P[j], 1)}%\n')
                else:
                    result_text.insert(tk.END, f'歼灭的概率为：{round(100 * P[j], 1)}%\n')
            result_text.insert(tk.END, '=========================================\n')
        except Exception as e:
            messagebox.showerror("错误", f"输入无效: {e}")

    # 创建防空武器窗口
    air_defense_window = tk.Toplevel()
    air_defense_window.title("防空武器分析")
    
    # 武器类型
    tk.Label(air_defense_window, text="防空武器:").grid(row=0, column=0, padx=5, pady=5)
    weapon_options = ["1.速射炮", "2.便携导弹", "3.防空高炮", "4.便携防空导弹", "5.车载防空导弹"]
    weapon_combobox = ttk.Combobox(air_defense_window, values=weapon_options)
    weapon_combobox.grid(row=0, column=1, padx=5, pady=5)
    weapon_combobox.set(weapon_options[0])
    
    # 攻击距离
    tk.Label(air_defense_window, text="攻击距离:").grid(row=1, column=0, padx=5, pady=5)
    distance_entry = tk.Entry(air_defense_window)
    distance_entry.grid(row=1, column=1, padx=5, pady=5)
    
    # 计算和清除按钮
    button_frame = tk.Frame(air_defense_window)
    button_frame.grid(row=2, column=0, columnspan=2, pady=10)
    
    calculate_button = tk.Button(button_frame, text="计算", command=calculate)
    calculate_button.pack(side="left", padx=5)
    
    clear_button = tk.Button(button_frame, text="清除", command=lambda: result_text.delete(1.0, tk.END))
    clear_button.pack(side="left", padx=5)
    
    # 结果显示
    result_text = tk.Text(air_defense_window, height=10, width=50)
    result_text.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

# 主窗口
def main():
    root = ttk.Window(themename="yeti")
    root.title("兵棋推演打击裁决分析器")
    
    # 版权信息
    tk.Label(root, text="<<<<<版权申明>>>>>").pack(pady=5)
    tk.Label(root, text="该软件用于兵棋推演打击裁决分析", width=20, anchor="w", justify="left").pack(fill="x", padx=10)
    tk.Label(root, text="版本号：v1.0", width=20, anchor="w", justify="left").pack(fill="x", padx=10)
    tk.Label(root, text="内部测试使用，转载请征得同意，如遇bug，欢迎反馈", width=20, anchor="w", justify="left").pack(fill="x", padx=10)
    tk.Label(root, text="开发团队：天钺策", width=20, anchor="w", justify="left").pack(fill="x", padx=10)
    tk.Label(root, text="联系人：余秋伟（15399220084）", width=20, anchor="w", justify="left").pack(fill="x", padx=10)
    
    # 分隔线
    tk.Label(root, text="========================================").pack(pady=10)
    
    # 功能按钮
    tk.Button(root, text="直瞄武器打击分析", command=direct_attack_analysis).pack(pady=5)
    tk.Button(root, text="间瞄计划分析", command=indirect_attack_analysis).pack(pady=5)
    tk.Button(root, text="防空武器分析", command=air_defense_analysis).pack(pady=5)
    
    root.mainloop()

if __name__ == '__main__':
    main()